import time
import json
from xiaopy import *
from cotc import COTC

try:
    ui = xp.ui()
    region = ui.stringValue("region")
    use_previous_battle_sequence = ui.boolValue("use_previous_battle_sequence")
    if use_previous_battle_sequence:
        with open('memory_battle_1_sequence.txt', 'r') as f:
            battle_1_sequence = json.loads(f.read())
        with open('memory_battle_2_sequence.txt', 'r') as f:
            battle_2_sequence = json.loads(f.read())
    else:
        battle_1_sequence_string = ui.stringValue("battle_1_sequence").replace(" ", "").replace("\n", "")
        battle_2_sequence_string = ui.stringValue("battle_2_sequence").replace(" ", "").replace("\n", "")
        battle_1_sequence = json.loads(battle_1_sequence_string)
        battle_2_sequence = json.loads(battle_2_sequence_string)
        with open('memory_battle_1_sequence.txt', 'w') as f:
            f.write(battle_1_sequence_string)
        with open('memory_battle_2_sequence.txt', 'w') as f:
            f.write(battle_2_sequence_string)
    c = COTC(region)
except Exception as e:
    xp.toast(e)


def run_script():
    total_count = 0
    while True:
        total_count += 1
        xp.log("第" + str(total_count) + "轮")
        start_time = time.time()

        # 战斗前
        c.tap_memories_read()
        c.tap_until_black_screen([798, 600])
        c.await_black_screen_transition()
        xp.tap(640, 360, 2.5)
        time.sleep(0.5)
        c.await_black_screen_transition()

        # 战斗 - 1
        c.run_preset_battle_sequence(battle_1_sequence)
        c.await_black_screen_transition()
        xp.tap(640, 360, 2.5)
        time.sleep(0.5)
        c.await_black_screen_transition()

        # 战斗 - 2
        c.run_preset_battle_sequence(battle_2_sequence)
        c.await_black_screen_transition()
        xp.tap(640, 360, 2.5)
        time.sleep(0.5)
        c.await_black_screen_transition()

        # 战斗后
        c.tap_memories_ok_after_battle()

        xp.log("本轮用时：" + str(int(time.time() - start_time)) + "秒")
        xp.log("------------------------")


run_script()
